package filterpkg;

import java.io.IOException;
import java.net.URLDecoder;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dao.NewsusersDao;
import entity.News_users;

public class CookieFilter implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
			throws IOException, ServletException {
		/*HttpServletRequest req=(HttpServletRequest) arg0;
		Cookie[] cookie = req.getCookies();
		String uname = "";
		String upwd = "";
		if (cookie != null) {
			for (int i = 0; i < cookie.length; i++) {
				if (cookie[i].getName().equals("NAME")) {
					uname =URLDecoder.decode(cookie[i].getValue(),"utf-8");
				}
				if (cookie[i].getName().equals("PASS")) {
					upwd = cookie[i].getValue();
				}
			}
		}
		req.getRequestDispatcher("index.jsp?uname="+uname+"&upwd="+upwd).forward(arg0, arg1);*/
		HttpServletRequest request = (HttpServletRequest) arg0;
		HttpServletResponse response=(HttpServletResponse) arg1;
		try {
			if (request.getSession().getAttribute("USER_login") == null) {
				String uname = null;
				String upwd = null;
				Cookie[] cookies = request.getCookies();
				if (cookies != null) {
					for (Cookie cookie : cookies) {
						if (cookie.getName().equals("NAME")) {
							uname = URLDecoder.decode(cookie.getValue(),
									"utf-8");
						}
						if (cookie.getName().equals("PASS")) {
							upwd = URLDecoder
									.decode(cookie.getValue(), "utf-8");
						}
					}
					News_users users = null;
					if (uname == null || upwd == null) {
						return;
					}
					NewsusersDao newsusersDao = new NewsusersDao();
					users= newsusersDao.login(uname, upwd);
					if (users != null) {
						HttpSession session = request.getSession();
						session.setAttribute("ADMIN", users);

					}else{
						Cookie c1=new Cookie("NAME", uname);
						c1.setMaxAge(0);
						response.addCookie(c1);
						Cookie c2=new Cookie("PASS", upwd);
						c2.setMaxAge(0);
						response.addCookie(c2);
						
					}
				}
			}
		} finally {
			arg2.doFilter(arg0, arg1);
		}

	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}
